import React from 'react';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { withRouter, router } from 'umi';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { message, Form, Input, Icon, Popover, Spin } from 'antd';

import {
    InterviewBoxPcB,
    InterviewDetail,
    ButtonPc as Button,
    InputPassword
} from '@/pages/RecruitEmail/pc/components';
import { useOldLogin } from '@/pages/RecruitEmail/hooks';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { updatePassword, getCheckAccount, getLoginInfo } from '@/pages/RecruitEmail/service/interview';
import pic from '@/pages/RecruitEmail/images/interview-bg-refuse.png';
import picLogin from '@/pages/RecruitEmail/images/interview-bg-new.png';
import styles from './index.less';

const OldLogin = ({ form, location }) => {
    const { query, pathname } = location;

    const { getFieldDecorator } = form;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [title, setTitle] = React.useState('');
    const [content, setContent] = React.useState('');

    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const [modifyPwdSafetyCode, setModifyPwdSafetyCode] = React.useState(false);
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { loading: loginLoading, handleLogin } = useOldLogin(location);

    React.useEffect(() => {
        if (modifyPwdSafetyCode) {
            setTitle('请设置密码并登录');
            setContent('微微科技为你开通了候选人帐号');
        } else {
            setTitle('你好，欢迎应聘微微科技有限公司');
            setContent('');
        }
    }, [modifyPwdSafetyCode]);
    const getAccount = async talentEmail => {
        let otherPara = {};
        if (pathname.includes('interview')) {
            otherPara = { interviewNoticeId: query?.id };
        } else if (pathname.includes('candidate')) {
            otherPara = { backgroundId: query?.signCandidateId };
        } else if (pathname.includes('hireConfirm')) {
            otherPara = { employId: query?.employId };
        } else {
            otherPara = query;
        }

        try {
            setSubmitLoading(true);
            const result = await getCheckAccount(talentEmail, otherPara);
            const { code, data, msg } = result;
            if (code === 10000) {
                const { candidateLinkId, hasCandidateAccount } = data;
                if (!hasCandidateAccount) {
                    if (modifyPwdSafetyCode) {
                        return candidateLinkId;
                    }
                    setModifyPwdSafetyCode(true);
                    form.resetFields(['password', 'password2']);
                    message.info('候选人尚未有账号，请先设置账号');
                    setSubmitLoading(false);
                    return null;
                }
                return candidateLinkId;
            }
            message.error(msg);
            setSubmitLoading(false);
            return null;
        } catch (error) {
            setSubmitLoading(false);
            return null;
        }
    };
    const forget = async () => {
        try {
            setSubmitLoading(true);
            const email = form.getFieldValue('talentEmail') || '';
            const id = await getAccount(email);
            setSubmitLoading(false);
            if (id) {
                history.push({
                    pathname: '/external/interview/resetPassword',
                    query: {
                        email: form.getFieldValue('talentEmail'),
                        id
                    }
                });
            }
        } catch (error) {
            setSubmitLoading(false);
        }
    };
    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                setSubmitLoading(true);
                // 设置账号
                if (modifyPwdSafetyCode) {
                    try {
                        // 创建账号
                        const id = await getAccount(values.talentEmail);
                        console.log('candidateLinkId000---', id);
                        if (id) {
                            // 获取登录信息
                            const loginInfo = await getLoginInfo(id);

                            if (loginInfo?.code === 10000) {
                                const data = loginInfo?.data;
                                if (data?.modifyPwdSafetyCode) {
                                    const updateResult = await updatePassword({
                                        key: data?.modifyPwdSafetyCode,
                                        password: values.password
                                    });
                                    if (updateResult?.code === 10000) {
                                        await handleLogin({
                                            talentEmail: values?.talentEmail,
                                            password: values.password,
                                            id
                                        });
                                        setSubmitLoading(false);
                                    } else {
                                        setSubmitLoading(false);
                                        message.error(updateResult?.msg);
                                    }
                                } else {
                                    await handleLogin({
                                        talentEmail: values?.talentEmail,
                                        password: values.password,
                                        id
                                    });
                                    setSubmitLoading(false);
                                }
                            } else {
                                setSubmitLoading(false);
                                message.error(loginInfo?.msg);
                            }
                        }
                    } catch (error) {
                        setSubmitLoading(false);
                    }
                } else {
                    try {
                        // 获取id
                        const id = await getAccount(values.talentEmail);
                        if (id) {
                            await handleLogin({
                                talentEmail: values?.talentEmail,
                                password: values.password,
                                id
                            });
                            setSubmitLoading(false);
                        }
                    } catch (error) {
                        setSubmitLoading(false);
                    }
                }
            }
        });
    };

    const detailStyle = {
        keyStyle: {
            color: '#BCC1CD',
            fontWeight: 500
        },
        valueStyle: {
            color: '#2A2F3C'
        }
    };

    const renderRightView = () => (
        <div style={{ width: 392, boxSizing: 'borderBox', margin: '0 auto' }}>
            <div style={{ marginTop: '110px' }}>
                <InterviewDetail
                    style={{ padding: 0, margin: 0 }}
                    dataSource={[
                        {
                            key: '账号',
                            showIcon: false,
                            render: (
                                <span
                                    style={{
                                        display: 'block',
                                        marginBottom: '8px',
                                        height: '24px',
                                        lineHeight: '24px',
                                        fontSize: 16,
                                        fontFamily: 'PingFangSC-Regular, PingFang SC',
                                        fontWeight: 400,
                                        color: 'rgba(0,0,0,0.65)'
                                    }}
                                >
                                    <div style={{ whiteSpace: 'pre', display: 'inline-block' }}>账号：</div>
                                </span>
                            ),
                            value: (
                                <Form.Item label="" colon={false} className={styles.formItemWrap}>
                                    <Popover
                                        placement="right"
                                        content={
                                            <div
                                                style={{
                                                    width: 210,
                                                    boxSizing: 'border-box',
                                                    display: 'flex'
                                                }}
                                            >
                                                <Icon
                                                    type="close-circle"
                                                    theme="filled"
                                                    style={{
                                                        marginRight: '4px',
                                                        color: '#F55656',
                                                        paddingTop: '4px'
                                                    }}
                                                />
                                                <div>
                                                    {form.getFieldError('talentEmail')
                                                        ? form.getFieldError('talentEmail')[0]
                                                        : ''}
                                                </div>
                                            </div>
                                        }
                                        visible={!!form.getFieldError('talentEmail')}
                                    >
                                        {getFieldDecorator('talentEmail', {
                                            initialValue: '',
                                            rules: [
                                                {
                                                    required: true,
                                                    whiteSpace: true,
                                                    message: '请输入邮箱'
                                                },
                                                {
                                                    validator(rule, value, callback) {
                                                        const regex = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
                                                        if (value) {
                                                            const tempValue = value.trim();
                                                            if (regex.test(tempValue)) {
                                                                callback();
                                                            } else {
                                                                callback('请输入正确的个人邮箱');
                                                            }
                                                        }
                                                        callback();
                                                    }
                                                }
                                            ]
                                        })(<Input placeholder="请输入邮箱" />)}
                                    </Popover>
                                </Form.Item>
                            )
                        }
                    ]}
                />

                <InterviewDetail
                    style={{ padding: 0, margin: 0 }}
                    dataSource={[
                        {
                            key: '设置密码',
                            showIcon: false,
                            render: (
                                <span
                                    style={{
                                        display: 'block',
                                        marginBottom: '8px',
                                        height: '24px',
                                        lineHeight: '24px',
                                        fontSize: 16,
                                        fontFamily: 'PingFangSC-Regular, PingFang SC',
                                        fontWeight: 400,
                                        color: 'rgba(0,0,0,0.65)'
                                    }}
                                >
                                    设置密码
                                </span>
                            ),
                            value: (
                                <Form.Item label="" colon={false} className={styles.formItemWrap}>
                                    <Popover
                                        placement="right"
                                        content={
                                            <div
                                                style={{
                                                    width: 210,
                                                    boxSizing: 'border-box',
                                                    display: 'flex'
                                                }}
                                            >
                                                <Icon
                                                    type="close-circle"
                                                    theme="filled"
                                                    style={{
                                                        marginRight: '4px',
                                                        color: '#F55656',
                                                        paddingTop: '4px'
                                                    }}
                                                />
                                                <div>
                                                    {form.getFieldError('password')
                                                        ? form.getFieldError('password')[0]
                                                        : ''}
                                                </div>
                                            </div>
                                        }
                                        visible={!!form.getFieldError('password')}
                                    >
                                        {getFieldDecorator('password', {
                                            rules: [
                                                {
                                                    required: true,
                                                    whiteSpace: true,
                                                    message: '请输入密码'
                                                },
                                                {
                                                    validator(rule, value, callback) {
                                                        const regex = /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).*$/;
                                                        if (value) {
                                                            const tempValue = value.trim();
                                                            if (
                                                                tempValue.length >= 8 &&
                                                                tempValue.length <= 20 &&
                                                                regex.test(value)
                                                            ) {
                                                                callback();
                                                            } else {
                                                                callback(
                                                                    '长度为8-20个字符，需同时包含大小写字母及数字'
                                                                );
                                                            }
                                                        }
                                                        callback();
                                                    }
                                                }
                                            ]
                                        })(
                                            <InputPassword
                                                placeholder="请输入密码"
                                                minLength={8}
                                                maxLength={20}
                                                allowClear
                                            />
                                        )}
                                    </Popover>
                                </Form.Item>
                            )
                        }
                    ]}
                />
            </div>
            <InterviewDetail
                style={{ padding: 0, margin: 0 }}
                dataSource={[
                    {
                        key: '确认密码',
                        render: (
                            <span
                                style={{
                                    height: '24px',
                                    lineHeight: '24px',
                                    fontSize: 16,
                                    fontFamily: 'PingFangSC-Regular, PingFang SC',
                                    fontWeight: 400,
                                    color: 'rgba(0,0,0,0.65)',
                                    display: 'block',
                                    marginBottom: '8px'
                                }}
                            >
                                确认密码
                            </span>
                        ),
                        value: (
                            <Form.Item label="" colon={false} className={styles.formItemWrap}>
                                <Popover
                                    placement="right"
                                    content={
                                        <div
                                            style={{
                                                width: 210,
                                                boxSizing: 'border-box',
                                                display: 'flex'
                                            }}
                                        >
                                            <Icon
                                                type="close-circle"
                                                theme="filled"
                                                style={{
                                                    marginRight: '4px',
                                                    color: '#F55656',
                                                    paddingTop: '4px'
                                                }}
                                            />
                                            <div>
                                                {form.getFieldError('password2')
                                                    ? form.getFieldError('password2')[0]
                                                    : ''}
                                            </div>
                                        </div>
                                    }
                                    visible={!!form.getFieldError('password2')}
                                >
                                    {getFieldDecorator('password2', {
                                        rules: [
                                            {
                                                required: true,
                                                whiteSpace: true,
                                                message: '请输入确认密码'
                                            },
                                            {
                                                validator(rule, value, callback) {
                                                    if (value) {
                                                        const tempValue = value.trim();
                                                        const password = form.getFieldValue('password').trim();
                                                        if (tempValue === password) {
                                                            callback();
                                                        } else {
                                                            callback('两次输入的密码不相同');
                                                        }
                                                    }
                                                    callback();
                                                }
                                            }
                                        ]
                                    })(
                                        <InputPassword
                                            placeholder="请输入密码"
                                            minLength={8}
                                            maxLength={20}
                                            allowClear
                                        />
                                    )}
                                </Popover>
                            </Form.Item>
                        )
                    }
                ]}
                {...detailStyle}
            />
            <div
                style={{
                    marginTop: 16,
                    marginBottom: modifyPwdSafetyCode ? '68px' : '215px',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'flex-end'
                }}
            >
                <Button type="primary" style={{ width: '100%' }} loading={submitLoading} onClick={handleSubmit}>
                    设置密码，前往登录
                </Button>
            </div>
        </div>
    );

    return (
        <div className={styles.interviewPc}>
            {/* <Spin spinning={loading}> */}
            <InterviewBoxPcB
                titleProps={{
                    src: modifyPwdSafetyCode ? pic : picLogin,
                    // titleAfter: companyName,
                    title,
                    content,
                    picStyle: { marginBottom: 24, marginLeft: modifyPwdSafetyCode ? 22 : 138 },
                    showStep: false,
                    wrap: true
                }}
                showLeftRight={false}
                // left={modifyPwdSafetyCode ? renderLeftView() : null}
                left={modifyPwdSafetyCode ? renderRightView() : null}
                // leftStyle={modifyPwdSafetyCode ? { width: '49%' } : {}}
                // rightStyle={modifyPwdSafetyCode ? { width: '49%' } : {}}
            >
                <div style={{ width: 392, boxSizing: 'borderBox', margin: '0 auto' }}>
                    <div style={{ marginTop: '163px' }}>
                        <InterviewDetail
                            style={{ padding: 0, margin: 0 }}
                            dataSource={[
                                {
                                    key: '账号',
                                    showIcon: false,
                                    render: (
                                        <span
                                            style={{
                                                display: 'block',
                                                marginBottom: '8px',
                                                height: '24px',
                                                lineHeight: '24px',
                                                fontSize: 16,
                                                fontFamily: 'PingFangSC-Regular, PingFang SC',
                                                fontWeight: 400,
                                                color: 'rgba(0,0,0,0.65)'
                                            }}
                                        >
                                            <div style={{ whiteSpace: 'pre', display: 'inline-block' }}>账号：</div>
                                        </span>
                                    ),
                                    value: (
                                        <Form.Item label="" colon={false} className={styles.formItemWrap}>
                                            <Popover
                                                placement="right"
                                                content={
                                                    <div
                                                        style={{
                                                            width: 210,
                                                            boxSizing: 'border-box',
                                                            display: 'flex'
                                                        }}
                                                    >
                                                        <Icon
                                                            type="close-circle"
                                                            theme="filled"
                                                            style={{
                                                                marginRight: '4px',
                                                                color: '#F55656',
                                                                paddingTop: '4px'
                                                            }}
                                                        />
                                                        <div>
                                                            {form.getFieldError('talentEmail')
                                                                ? form.getFieldError('talentEmail')[0]
                                                                : ''}
                                                        </div>
                                                    </div>
                                                }
                                                visible={!!form.getFieldError('talentEmail')}
                                            >
                                                {getFieldDecorator('talentEmail', {
                                                    initialValue: '',
                                                    rules: [
                                                        {
                                                            required: true,
                                                            whiteSpace: true,
                                                            message: '请输入邮箱'
                                                        },
                                                        {
                                                            validator(rule, value, callback) {
                                                                const regex = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
                                                                if (value) {
                                                                    const tempValue = value.trim();
                                                                    if (regex.test(tempValue)) {
                                                                        callback();
                                                                    } else {
                                                                        callback('请输入正确的个人邮箱');
                                                                    }
                                                                }
                                                                callback();
                                                            }
                                                        }
                                                    ]
                                                })(<Input placeholder="请输入邮箱" />)}
                                            </Popover>
                                        </Form.Item>
                                    )
                                }
                            ]}
                        />
                        <InterviewDetail
                            style={{ padding: 0, margin: 0 }}
                            dataSource={[
                                {
                                    key: '密码',
                                    showIcon: false,
                                    render: (
                                        <span
                                            style={{
                                                display: 'block',
                                                marginBottom: '8px',
                                                height: '24px',
                                                lineHeight: '24px',
                                                fontSize: 16,
                                                fontFamily: 'PingFangSC-Regular, PingFang SC',
                                                fontWeight: 400,
                                                color: 'rgba(0,0,0,0.65)'
                                            }}
                                        >
                                            <div style={{ whiteSpace: 'pre', display: 'inline-block' }}>密码：</div>
                                        </span>
                                    ),
                                    value: (
                                        <Form.Item label="" colon={false} className={styles.formItemWrap}>
                                            <Popover
                                                placement="right"
                                                content={
                                                    <div
                                                        style={{
                                                            width: 210,
                                                            boxSizing: 'border-box',
                                                            display: 'flex'
                                                        }}
                                                    >
                                                        <Icon
                                                            type="close-circle"
                                                            theme="filled"
                                                            style={{
                                                                marginRight: '4px',
                                                                color: '#F55656',
                                                                paddingTop: '4px'
                                                            }}
                                                        />
                                                        <div>
                                                            {form.getFieldError('password')
                                                                ? form.getFieldError('password')[0]
                                                                : ''}
                                                        </div>
                                                    </div>
                                                }
                                                visible={!!form.getFieldError('password')}
                                            >
                                                {getFieldDecorator('password', {
                                                    rules: [
                                                        {
                                                            required: true,
                                                            whiteSpace: true,
                                                            message: '请输入密码'
                                                        },
                                                        {
                                                            validator(rule, value, callback) {
                                                                const regex = /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).*$/;
                                                                if (value) {
                                                                    const tempValue = value.trim();
                                                                    if (
                                                                        tempValue.length >= 8 &&
                                                                        tempValue.length <= 20 &&
                                                                        regex.test(value)
                                                                    ) {
                                                                        callback();
                                                                    } else {
                                                                        callback(
                                                                            '长度为8-20个字符，需同时包含大小写字母及数字'
                                                                        );
                                                                    }
                                                                }
                                                                callback();
                                                            }
                                                        }
                                                    ]
                                                })(
                                                    <InputPassword
                                                        placeholder="请输入密码"
                                                        minLength={8}
                                                        maxLength={20}
                                                        allowClear
                                                    />
                                                )}
                                            </Popover>
                                        </Form.Item>
                                    )
                                }
                            ]}
                        />
                    </div>

                    <div className={styles.loginBtns} style={{ marginBottom: modifyPwdSafetyCode ? '68px' : '215px' }}>
                        <Button type="primary" style={{ width: '100%' }} loading={loginLoading} onClick={handleSubmit}>
                            登录
                        </Button>
                        <div className={styles.bottomAContainer}>
                            <div className={styles.bottomA}>
                                <span>没有账号？</span>
                                <a
                                    style={{ color: 'rgb(45, 135, 255)' }}
                                    onClick={e => {
                                        e.preventDefault();
                                        setModifyPwdSafetyCode(true);
                                        form.resetFields(['password', 'password2']);
                                    }}
                                >
                                    创建账号
                                </a>
                            </div>

                            <a
                                style={{ color: 'rgb(45, 135, 255)' }}
                                className={styles.bottomA}
                                onClick={async () => {
                                    forget();
                                }}
                            >
                                忘记密码
                            </a>
                        </div>
                    </div>
                </div>
            </InterviewBoxPcB>
            {/* </Spin> */}
        </div>
    );
};

export default withRouter(Form.create({})(OldLogin));
